package zsc.liangyi.blog.web.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import zsc.liangyi.blog.model.ResponseData.ResponseData;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.service.UserService;
import zsc.liangyi.blog.service.impl.UserDetailsServiceImpl;
import zsc.liangyi.blog.utils.EmailUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private EmailUtils emailUtils;
    //向登录页面跳转
    @GetMapping("/login")
    public String toLogin(){
        System.out.println("/login");
        return "comm/login";
    }

    @GetMapping("/login?error")
    @ResponseBody
    public String errorLogin(){
        System.out.println("/login?error");
        return "用户名或密码错误";
    }

    @GetMapping("/forget")
    public String forget(){
        return "comm/find_me";
    }

    //发送验证码
    @PostMapping("/forget/code")
    @ResponseBody
    public ResponseData code(@RequestParam(value = "email") String email,
                               @RequestParam(value = "username") String username){
        //逻辑
        // 获取用户
        User user=userService.getByUserName(username);
        if(user==null){
            return ResponseData.fail("无此用户");
        }
        //1.获取用户邮箱
        if(StringUtils.isBlank(email)||!user.getEmail().equals(email)){
            return ResponseData.fail("请输入正确邮箱");
        }
        String receiver=email;
        //2.随机生成4位验证码
        String code="xxxx";
        //3.往邮箱发送验证码与正文
         String subject="找回密码-验证码";
        Context context=new Context();
        context.setVariable("code",code);
        context.setVariable("username",username);
        String emailContent = templateEngine.process("email/code", context);
        emailUtils.sendCode(receiver,subject,emailContent);
        //4.将验证码存入redis，有效期为5分钟
        redisTemplate.opsForValue().set("code_"+username,code,5*60, TimeUnit.SECONDS);
        //5.将验证码与有效期返回前端
        return ResponseData.success();
    }


    @PostMapping("/forget")
    @ResponseBody
    public ResponseData forgetPassword(@RequestParam(value = "email") String email,
                                       @RequestParam(value = "username") String username,
                                       @RequestParam(value = "code" ,required = false) String code,
                                       @RequestParam(value = "password",required = false) String password){
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        User user=userService.getByUserName(username);
        if(user==null){
            return ResponseData.fail("无此用户，请检查用户名");
        }else if(!user.getEmail().equals(email)){
            return ResponseData.fail("邮箱信息错误，请检查重新输入");
        }
        log.info("验证成功");
        //验证成功
        try{
            if(StringUtils.isBlank(password)){
                return ResponseData.fail("请输入新密码");
            }
            if(code.equals(redisTemplate.opsForValue().get("code_"+username))){
                user.setPassword(encoder.encode(password));
                userService.update(user);
                return ResponseData.success("修改密码成功，请返回登录");
            }else{
                return ResponseData.fail("验证码错误");
            }

        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail("修改密码失败");
        }
    }


}
